<template>
  <div class="app-container">
    <el-row :gutter="50">
      <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
        <p>商品列表 <el-input v-model="inputVal" style="width: 240px" placeholder="输入商品名称" clearable
            @clear='clear' @input='search'>
          </el-input>
          <el-button v-if="listVal.length>1" icon="ArrowUp" @click="ArrowUp" />
          <el-button v-if="listVal.length>1" icon="ArrowDown" @click="ArrowDown" />
          <span v-if="listVal.length>1">{{indexId+1}}/{{listVal.length}}</span>
          <el-button icon="Refresh" @click="resetQuery">刷新</el-button>
        </p>
        <draggable class="list-group1" id="list-group1" v-model="list1" :clone="clone"
          :group="{ name: 'people', pull: pullFunction }" @start="start" item-key="id" @end='end'
          :style="{'maxHeight': tableHeight}" :scroll-sensitivity="150" :scroll-speed="10"
          :scroll="true" :bubble-scroll="false" :animation="300">
          <template #item="{ element }">
            <div class="list-group-item " :id="element.id"
              :class="{'Achecked':listVal[indexId]==element.id }">
              <el-badge :value="element.hot1" class="item">
                <img :src="element.coImage" alt="" width="60" height="60">
              </el-badge>
              <p>{{ element.name }}</p>
            </div>
          </template>
        </draggable>
      </el-col>

    </el-row>

  </div>
</template>
<script setup>
import { defineComponent, reactive, ref, toRefs, toRaw } from "vue";
import useUserStore from "@/store/modules/user";
const { proxy } = getCurrentInstance();
const userStore = useUserStore();
import {
  HomeProductlist,
  HomeProductSort,
  HomeProductSearch,
} from "@/api/commodityMgt/commodityHome/commodity";
const list1 = ref([]);
const list2 = ref([]);
const data = reactive({
  queryParams: {
    shopId: userStore.userDta.shopId,
    page: 1,
    limit: 1000,
  },
});
const inputVal = ref("");
const draggableSta = ref(".list-group-item1");
const elementVal = ref(""); //拖动值
const newIndexVal = ref("");
const controlOnStart = ref(true);
const searchFsta = ref(true);
function clone(element) {
  draggableSta.value = ".list-group-item";
  elementVal.value = element;
  return element;
}
const tableHeight = ref("calc(100vh - 400px)"); // 假设顶部保留200px
function handleResize() {
  let hight = 200 + "px";
  tableHeight.value = `calc(100vh - ` + hight + `)`;
}
onMounted(async () => {
  await nextTick();
  let hight = 200 + "px";
  tableHeight.value = `calc(100vh - ` + hight + `)`;
  window.addEventListener("resize", handleResize);
});
// 移除事件监听器以防止内存泄漏
onUnmounted(() => {
  window.removeEventListener("resize", handleResize);
});
function onAdd(event) {
  // 这里可以获取拖动项的位置
  // 使用 $event.to 和 $event.oldIndex 可以获取新旧数组的位置
  const oldIndex = event.oldIndex;
  const newIndex = event.newIndex;
  // newIndexVal.value = newIndex;
}
function end(event) {
  const oldIndex = event.oldIndex;
  const newIndex = event.newIndex;
  const movedItem = event.to.className;
  if (oldIndex == newIndex) {
    return false;
  }
  newIndexVal.value = newIndex;
  for (let i = 0; i < list1.value.length; i++) {
    list1.value[i].hot1 = i + 1;
  }

  let obj = {
    toaId: "",
    tobId: "",
    fromId: elementVal.value.id,
  };
  if (newIndexVal.value == 0) {
    obj.toaId = 0;
    obj.tobId = list1.value[1].id;
  } else if (newIndexVal.value == list1.value.length - 1) {
    obj.toaId = list1.value[list1.value.length - 2].id;
    obj.tobId = 0;
  } else {
    obj.toaId = list1.value[newIndexVal.value - 1].id;
    obj.tobId = list1.value[newIndexVal.value + 1].id;
  }
  console.log(obj, "======", list1.value);
  HomeProductSort(obj)
    .then((res) => {
      if (res.status == 200) {
        proxy.$modal.msgSuccess("OK");
      }
    })
    .catch(() => {
      Productlist(1);
    });
}
const listVal = ref([]);
const indexId = ref(0);
function clear() {
  listVal.value = [];
  searchFsta.value = true;
}
const ArrowUp = () => {
  if (indexId.value == 0) {
    indexId.value = listVal.value.length - 1;
  } else {
    indexId.value = indexId.value - 1;
  }

  const anchorElement = document.getElementById(listVal.value[indexId.value]);
  if (anchorElement) {
    anchorElement.scrollIntoView({ behavior: "smooth" });
  }
};
const ArrowDown = () => {
  console.log(listVal.value.length, indexId.value);
  if (listVal.value.length - 1 == indexId.value) {
    indexId.value = 0;
  } else {
    indexId.value = indexId.value + 1;
  }
  const anchorElement = document.getElementById(listVal.value[indexId.value]);
  if (anchorElement) {
    anchorElement.scrollIntoView({ behavior: "smooth" });
  }
};
// 搜索商品
function search() {
  let arrList = [];
  indexId.value = 0;
  searchFsta.value = false;
  for (let i = 0; i < list1.value.length; i++) {
    if (list1.value[i].name.indexOf(inputVal.value) != -1) {
      arrList.push(list1.value[i].id);
    }
  }
  if (!inputVal.value.trim()) {
    arrList = [];
  }
  listVal.value = arrList;
  console.log(listVal.value);
  if (listVal.value.length != 0) {
    const anchorElement = document.getElementById(arrList[indexId.value]);
    if (anchorElement) {
      anchorElement.scrollIntoView({ behavior: "smooth" });
    }
  }
}
function pullFunction() {
  return controlOnStart.value ? "clone" : true;
}
function start({ originalEvent }) {
  controlOnStart.value = originalEvent.ctrlKey;
}

const { queryParams } = toRefs(data);

const Productlist = (sta) => {
  let dataObj = {
    shopId: queryParams.value.shopId,
    page: queryParams.value.page,
    limit: queryParams.value.limit,
  };
  HomeProductlist(dataObj).then((res) => {
    for (let i = 0; i < res.data.length; i++) {
      res.data[i].coImage =
        "https://jzh-newhxd.oss-cn-qingdao.aliyuncs.com/" +
        res.data[i].image.split(",")[0];
    }
    for (let i = 0; i < res.data.length; i++) {
      res.data[i].hot1 = i + 1;
    }
    list1.value = res.data;
    if (sta == 2) {
      proxy.$modal.msgSuccess("已更新");
    }
  });
};
Productlist(1);
const resetQuery = () => {
  Productlist(2);
};
</script>
<style lang="scss" scoped >
.list-group2,
.list-group1 {
  display: flex;
  flex-wrap: wrap;
  .list-group-item {
    width: 100px;
    height: 150px;
    margin-top: 5px;
    margin-right: 5px;
    border: 1px solid #ccc;
    display: flex;
    flex-direction: column;
    justify-content: space-between;

    align-items: center;
    p {
      max-width: 90px;
      overflow: hidden;
      text-overflow: ellipsis;
      -webkit-line-clamp: 2;
      word-wrap: break-word;
      display: -webkit-box;
      -webkit-box-orient: vertical;
    }
  }
}
#list-group1 {
  overflow-y: auto;
}
.Achecked {
  background-color: antiquewhite;
}
</style>
